package com.chenwang.measure.ui.dialog;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ProgressBar;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chenwang.measure.R;
import com.chenwang.measure.base.BaseDialogFragment;
import com.chenwang.measure.receiver.BtReceiver;
import com.chenwang.measure.ui.activity.BluetoothActivity;
import com.chenwang.measure.ui.adapter.BluetoothScanAdapter;
import com.chenwang.measure.utils.MyToast;
import com.chenwang.measure.utils.SharePreferenceUtils;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.inuker.bluetooth.library.utils.BluetoothUtils.unregisterReceiver;

/**
 * @松 on 2019/8/7 16:20
 * 与pc连接蓝牙界面
 */
public class TaskBuletoothDialog extends BaseDialogFragment implements BaseQuickAdapter.OnItemClickListener, BtReceiver.Listener {

    @BindView(R.id.rv)
    RecyclerView mRv;
    @BindView(R.id.spin_kit)
    ProgressBar mBar;
    @BindView(R.id.btn_scan)
    Button mBtnScan;
    Unbinder unbinder;

    private BluetoothAdapter mAdapter; //蓝牙适配器
    private BtReceiver mBtReceiver;
    private BluetoothScanAdapter mScanAdapter;//蓝牙列表适配
    private BluetoothDevice mDevice;  //保存最新配对成功的蓝牙设备

    @Override
    public int setLayoutId() {
        return R.layout.dialog_task_buletooth;
    }

    @Override
    protected void initWindow(Window window) {
        setLayoutParams(window, Gravity.CENTER, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, 0, 0);
    }

    @Override
    protected void initData(View view) {
        super.initData(view);
        unbinder = ButterKnife.bind(this, view);
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        mBtReceiver = new BtReceiver(getContext(), this); //注册蓝牙广播
        initRecycelrView();
        scan();
    }

    //初始化RecycelrView
    private void initRecycelrView() {
        mRv.setLayoutManager(new LinearLayoutManager(getContext()));
        mScanAdapter = new BluetoothScanAdapter(null);
        mScanAdapter.setOnItemClickListener(this);
        mRv.setAdapter(mScanAdapter);

    }

    private void scan() {

        if (mAdapter.isDiscovering()) {
            mAdapter.cancelDiscovery();
            mBtnScan.setText("开始扫描");
            mBtnScan.setBackgroundResource(R.drawable.corners6_blue);
            mBar.setVisibility(View.INVISIBLE);

        } else {
            mScanAdapter.clear();
            mAdapter.startDiscovery();
            mBtnScan.setText("停止扫描");
            mBtnScan.setBackgroundResource(R.drawable.corners6_red);
            mBar.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        getActivity().unregisterReceiver(mBtReceiver);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        mDevice = (BluetoothDevice) adapter.getData().get(position);
        try {
            if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) { MyToast.show("正在配对");
                Method createBondMethod = null;
                createBondMethod = BluetoothDevice.class.getMethod("createBond");
                Boolean result = (Boolean) createBondMethod.invoke(mDevice);
                if (result){
                    // mScanAdapter.notifyDataSetChanged();
                }else {
                    MyToast.show("配对失败");
                }
            } else if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
                MyToast.show("已配对 无需在配对");

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void foundDev(BluetoothDevice dev) {
        if (!TextUtils.isEmpty(dev.getName())) {
            mScanAdapter.addData(dev);
        }
    }


    //扫描结束
    @Override
    public void onScanFinished() {
        mBtnScan.setText("开始扫描");
        mBtnScan.setBackgroundResource(R.drawable.corners6_blue);
        mBar.setVisibility(View.INVISIBLE);

    }

    @Override
    public void onState(int state) {

        if (state == BluetoothDevice.BOND_BONDED){
            MyToast.show("配对成功");
            mScanAdapter.notifyDataSetChanged();
            showNormalDialog();

        }
    }
    private void showNormalDialog(){
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(getContext());
        normalDialog.setTitle(mDevice.getName()+"");
        normalDialog.setMessage("将此设备作为下载上传");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Set<BluetoothDevice> pairedDevices = mAdapter.getBondedDevices();
                        if (!TextUtils.isEmpty(SharePreferenceUtils.getString(getContext(),"pc_bluetooth_mac" , ""))){
                            for ( BluetoothDevice device: pairedDevices){
                                if (device.getAddress().equals(SharePreferenceUtils.getString(getContext(),"pc_bluetooth_mac" , ""))){
                                    unpairDevice(device);
                                    SharePreferenceUtils.putString(getContext(),"pc_bluetooth_mac" , "");
                                    SharePreferenceUtils.putString( getContext(),"pc_bluetooth_name" , "");
                                }
                            }
                        }
                        SharePreferenceUtils.putString(getContext(),"pc_bluetooth_mac" , mDevice.getAddress());
                        SharePreferenceUtils.putString( getContext(),"pc_bluetooth_name" , mDevice.getName());
                        dismiss();
                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        dialog.dismiss();
                    }
                });
        // 显示
        normalDialog.show();
    }



    @OnClick(R.id.btn_scan)
    public void onViewClicked() {
        scan();
    }

    private void unpairDevice(BluetoothDevice device) {
        try {
            Method m = device.getClass()
                    .getMethod("removeBond", (Class[]) null);
            m.invoke(device, (Object[]) null);
        } catch (Exception e) {

        }
    }
}
